function fsb_SPM(idat,sandbox)

% FSB: SPM interface GUI
%
% EXAMPLE: sandbox = fsb_SPM(idat,sandbox)
%
% INPUT:
% idat: 4D image data
% sandbox: sandbox experiment struct
%
% OUTPUT:
% sandbox: sandbox experiment data
%
% CALLED BY:
% FSB.m
%
% NOTES:
%
% Copyright 2010 MPI for Biological Cybernetics
% Author: Steffen Stoewer
% License:GNU GPL, no express or implied warranties
%
% $ Revision 1.0
%
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

%~~~~~~~~~~~~~~~~~~~~~~~~~~
% Check input arguments
%~~~~~~~~~~~~~~~~~~~~~~~~~~
if nargin<2
    disp('No data provided, aborting')
    return
end

warning off;
ropts.srt = 5;
ropts.ver = 'SPM5';
ropts.do = [0 0 0 0 0];
ropts.cov = 0;
ropts.what(1) = 1;
ropts.mask = [];
ropts.cvi = 'AR(1)';
ropts.global = 'None';
ropts.hpf = 'Inf';
ropts.derivs = [0 0];
ropts.lincomp = 0;
ropts.artmod = 0;
ropts.trialmod = 0;
ropts.trialintermod = 0;

%~~~~~~~~~~~~~~~~~~~~~~~~~~
% Set GUI up
%~~~~~~~~~~~~~~~~~~~~~~~~~~

SPMwindow = figure('Visible','off','Position',[100,300,550,350],'Resize','off','Toolbar','none','MenuBar','none','NumberTitle','off','Name','SPM interface GUI');
%figure(SPMwindow);

%~~~~~~~~~~~~~~~~~~~~~~~~~~
% Add Buttons and edit fields
%~~~~~~~~~~~~~~~~~~~~~~~~~~

uicontrol('Style','Pushbutton',...
    'Position',[40,150,120,25],...
    'String','Run Pipeline',...
    'TooltipString','Run SPM5 Analysis FE',...
    'Callback',{@run_pipeline_Callback});

% Currently disabled
% uicontrol('Style','Pushbutton',...
%     'Position',[180,150,120,25],...
%     'String', 'Test coregistration',...
%     'TooltipString', 'Test coregistration',...
%     'Callback',{@TestCoregistration_Callback});

h_realignselect = uicontrol('Style','radiobutton','String','Realign',...
    'Position',[240,310,90,25],...
    'TooltipString','Realign data',...
    'Callback',{@Realignselect_Callback});

h_coregisterselect = uicontrol('Style','radiobutton','String','Normalize',...
    'Position',[240,280,90,25],...
    'TooltipString','Run normalization to template',...
    'Callback',{@Coregisterselect_Callback});

h_smoothselect = uicontrol('Style','radiobutton','String','Smooth',...
    'Position',[240,250,90,25],...
    'TooltipString','Smooth data',...
    'Callback',{@Smoothselect_Callback});

h_smoothedit = uicontrol('Style','edit','String','2 2 2',...
    'Position',[297,252,30,20],'Visible','off',...
    'TooltipString','Select smoothing kernel',...
    'Callback',{@Smoothselect_Callback});

h_analysisselect = uicontrol('Style','radiobutton','String','Analysis',...
    'Position',[240,220,90,25],...
    'TooltipString','Run analysis',...
    'Callback',{@Analysisselect_Callback});

h_contrastselect = uicontrol('Style','radiobutton','String','Contrasts',...
    'Position',[240,190,90,25],...
    'TooltipString','Run contrasts',...
    'Callback',{@Contrastselect_Callback});

h_covariateselect = uicontrol('Style','radiobutton','String','Covariates',...
    'Position',[360,190,120,25],'Visible','off',...
    'TooltipString','Use Covariates for Eye, Jaw and Body movement',...
    'Callback',{@Covariateselect_Callback});

h_derivativesselect = uicontrol('Style','radiobutton','String','Derivatives',...
    'Position',[360,220,120,25],'Visible','off',...
    'TooltipString','Should time and dispersion derivatives be modelled?',...
    'Callback',{@Derivativesselect_Callback});

h_globalnormsselect = uicontrol('Style','radiobutton','String','Globnorm',...
    'Position',[360,250,120,25],'Visible','off',...
    'TooltipString','Should Global Normalization be run?',...
    'Callback',{@Globnormselect_Callback});

h_maskselect = uicontrol('Style','radiobutton','String','Masking',...
    'Position',[360,280,120,25],'Visible','off',...
    'TooltipString','Should images be masked for analysis?',...
    'Callback',{@Maskselect_Callback});

h_AR1select = uicontrol('Style','radiobutton','String','AR(1)',...
    'Position',[360,310,120,25],'Visible','off',...
    'TooltipString','Select if AR(1) correction should be applied',...
    'Callback',{@AR1select_Callback});

h_linear_components = uicontrol('Style','radiobutton','String','Linear Components',...
    'Position',[360,160,120,25],'Visible','off',...
    'TooltipString','Model linear components',...
    'Callback',{@lin_comp_select_Callback});

h_trialmodel = uicontrol('Style','radiobutton','String','Model Trials',...
    'Position',[360,130,120,25],'Visible','off',...
    'TooltipString','Label trials affected by artefacts',...
    'Callback',{@trialmodel_select_Callback});

h_artmodel = uicontrol('Style','radiobutton','String','Model Artefacts',...
    'Position',[360,100,120,25],'Visible','off',...
    'TooltipString','Label artefacts',...
    'Callback',{@artmodel_select_Callback});

h_highpassfilterselect = uicontrol('Style','radiobutton','String','Highpass',...
    'Position',[360,70,100,25],'Visible','off',...
    'TooltipString','Select High Pass Filter cutoff',...
    'Callback',{@highpassfilterselect_Callback});

h_highpassfiltervalue = uicontrol('Style','Edit','String','Inf',...
    'Position',[430,70,50,25],'Visible','off',...
    'TooltipString','Input high pass filter value',...
    'Callback',{@highpassfilterselect_Callback});

h_trial_inter_model = uicontrol('Style','radiobutton','String','Exclude intertrial',...
    'Position',[360,40,120,25],'Visible','off',...
    'TooltipString','Label intertrial periods',...
    'Callback',{@trial_inter_model_Callback});


%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
% Contrast vector callbacks
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

uicontrol('Style','Text','String','Contrast 1',...
    'Position',[20,32,80,15],...
    'TooltipString','Name of contrast 1');

h_contrast_name1 = uicontrol('Style','edit',...
    'Position',[100,30,80,20],...
    'String','Contrast 1','Visible','off',...
    'TooltipString','Edit Contrast name 1',...
    'Callback',{@Contrastname1_Callback});

h_contrast_vector1 = uicontrol('Style','edit',...
    'Position',[180,30,100,20],...
    'String','','Visible','off',...
    'TooltipString','Edit Contrast vector 1',...
    'Callback',{@Contrastname1_Callback});

uicontrol('Style','Text','String','Contrast 2',...
    'Position',[20,62,80,15],...
    'TooltipString','Name of contrast 2');

h_contrast_name2 = uicontrol('Style','edit',...
    'Position',[100,60,80,20],...
    'String','Contrast 2','Visible','off',...
    'TooltipString','Edit Contrast name 2',...
    'Callback',{@Contrastname2_Callback});

h_contrast_vector2 = uicontrol('Style','edit',...
    'Position',[180,60,100,20],...
    'String','','Visible','off',...
    'TooltipString','Edit Contrast vector 2',...
    'Callback',{@Contrastname2_Callback});

uicontrol('Style','Text','String','Contrast 3',...
    'Position',[20,92,80,15],...
    'TooltipString','Name of contrast 3');

h_contrast_name3 = uicontrol('Style','edit',...
    'Position',[100,90,80,20],...
    'String','Contrast 3','Visible','off',...
    'TooltipString','Edit Contrast name 3',...
    'Callback',{@Contrastname3_Callback});

h_contrast_vector3 = uicontrol('Style','edit',...
    'Position',[180,90,100,20],...
    'String','','Visible','off',...
    'TooltipString','Edit Contrast vector 3',...
    'Callback',{@Contrastname3_Callback});

uicontrol('Style','Text','String','Contrast 4',...
    'Position',[20,122,80,15],...
    'TooltipString','Name of contrast 4');

h_contrast_name4 = uicontrol('Style','edit',...
    'Position',[100,120,80,20],...
    'String','Contrast 1','Visible','off',...
    'TooltipString','Edit Contrast name 4',...
    'Callback',{@Contrastname4_Callback});

h_contrast_vector4 = uicontrol('Style','edit',...
    'Position',[180,120,100,20],...
    'String','','Visible','off',...
    'TooltipString','Edit Contrast vector 4',...
    'Callback',{@Contrastname4_Callback});


%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
% Button group for SPM Version used
% All versions besides SPM5 currently disabled
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

h1 = uibuttongroup('visible','off','Units','pixels','Position',[20 190 90 145]);

% x0 = uicontrol('Style','Radio','String','SPM99',...
%     'pos',[10 100 70 30],'parent',h1,'HandleVisibility','off');
 x1 = uicontrol('Style','Radio','String','SPM5',...
     'pos',[10 70 70 30],'parent',h1,'HandleVisibility','off');
% x2 = uicontrol('Style','Radio','String','SPM2',...
%     'pos',[10 40 70 30],'parent',h1,'HandleVisibility','off');
% x3 = uicontrol('Style','Radio','String','SPM99',...
%     'pos',[10 10 70 30],'parent',h1,'HandleVisibility','off');

set(h1,'SelectionChangeFcn',@Get_SPM_Version_Callback);
set(h1,'SelectedObject',x1);  % Select SPM5
set(h1,'Visible','on');

%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
% Button group for Analysis level selection
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
h = uibuttongroup('visible','off','Units','pixels','Position',[130 190 90 145]);

u0 = uicontrol('Style','Radio','String','Trial',...
    'pos',[10 100 70 30],'parent',h,'HandleVisibility','off');
u1 = uicontrol('Style','Radio','String','Run',...
    'pos',[10 70 70 30],'parent',h,'HandleVisibility','off');
u2 = uicontrol('Style','Radio','String','Session',...
    'pos',[10 40 70 30],'parent',h,'HandleVisibility','off');
u3 = uicontrol('Style','Radio','String','None',...
    'pos',[10 10 70 30],'parent',h,'HandleVisibility','off');

set(h,'SelectionChangeFcn',@Get_relevant_model_Callback);
set(h,'SelectedObject',u3);  % Select none
set(h,'Visible','on');

%~~~~~~~~~~~~~~~~~~~~~~~~~~
% Wait until user input is done
%~~~~~~~~~~~~~~~~~~~~~~~~~~

%idat(isnan(idat) ) = 0;
set(SPMwindow,'Visible','on');
axis off;

%uiwait;

% ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
% Button callbacks
% ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

% ropts: processing options with the fields
%       .do(1) = 1 : Do spatial preprocessing
%       .do(2) = 1 : Do realignment
%       .do(3) = 1 : Do smoothing
%       .do(4) = 1 : Set up and estimate analysis
%       .do(5) = 1 : Set up and estimate contrasts
%       .ver = SPM2 : Use SPM2 pipeline for analysis
%       .ver = SPM5 : Use SPM5 pipeline for analysis
%       .what = 1 : Realign and reslice the images
%       .what = 0 : Do create mean realigned images, but don't do reslicing
%       .cov = 0;
%       at this stage

%~~~~~~~~~~~~~~~~~~~~~~~~~~
% SPM selection callback
%~~~~~~~~~~~~~~~~~~~~~~~~~~

    function Get_SPM_Version_Callback(source,eventdata)

        % All versions other than SPM5 currently disabled

        selstr = get(eventdata.NewValue,'String');
        disp (selstr);
        switch selstr
            case 'SPM8'
                ropts.ver = 'SPM8';
            case 'SPM5'
                ropts.ver = 'SPM5';
            case 'SPM2'
                ropts.ver = 'SPM2';
            case 'SPM99'
                ropts.ver = 'SPM99';
        end

    end

%~~~~~~~~~~~~~~~~~~~~~~~~~~
% Model selection callback
%~~~~~~~~~~~~~~~~~~~~~~~~~~

    function Get_relevant_model_Callback(source,eventdata)


        selstr = get(eventdata.NewValue,'String');
        disp (selstr);
        switch selstr
            case 'None'
                ropts.srt = 1;
            case 'Session'
                ropts.srt = 5;
            case 'Run'
                ropts.srt = 4;
            case 'Trial'
                ropts.srt = 3;
        end
        fsb_show_design(sandbox,ropts)

    end


%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
% Select if Covariates for Eye and Body motion should be used
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    function Covariateselect_Callback(source, eventdata)

        if (get(h_covariateselect,'Value') == get(h_covariateselect,'Max')) ;
            ropts.cov = 1;
        else
            ropts.cov = 0;
        end

    end

%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
% Select if data should be coregistered with template
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    function Coregisterselect_Callback(source, eventdata)

        if (get(h_coregisterselect,'Value') == get(h_coregisterselect,'Max')) ;
            ropts.do(1) = 1;
            ropts.what(1) = 0;
        else
            ropts.do(1) = 0;
            ropts.what(1) = 1;
        end

    end

%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
% Select if data should be realigned
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    function Realignselect_Callback(source, eventdata)

        if (get(h_realignselect,'Value') == get(h_realignselect,'Max')) ;
            ropts.do(2) = 1;
            ropts.what(1) = 1;
        else
            ropts.do(2) = 0;
        end

    end

%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
% Select if dataset should be smoothed
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    function Smoothselect_Callback(source, eventdata)

       if (get(h_smoothselect,'Value') == get(h_smoothselect,'Max')) ;
            ropts.do(3) = 1;
            smoothing_kernel = get(h_smoothedit,'String');        
            ropts.smoothing_kernel = str2num(smoothing_kernel);
            set(h_smoothedit,'Visible','on');
        else
            ropts.do(3) = 0;
            set(h_smoothedit,'Visible','off');
        end

    end

%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
% Select if analysis should be run
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    function Analysisselect_Callback(source, eventdata)

        if (get(h_analysisselect,'Value') == get(h_analysisselect,'Max')) ;
            ropts.do(4) = 1;
            set(h_derivativesselect,'Visible','on');
            set(h_globalnormsselect,'Visible','on');
            set(h_highpassfilterselect,'Visible','on');
            set(h_highpassfiltervalue,'Visible','on');
            set(h_maskselect,'Visible','on');
            set(h_AR1select,'Visible','on');
            set(h_covariateselect,'Visible','on');
            set(h_linear_components,'Visible','on');
            set(h_artmodel,'Visible','on');
            set(h_trialmodel,'Visible','on');
            set(h_trial_inter_model,'Visible','on');
            
        else
            ropts.do(4) = 0;
            set(h_derivativesselect,'Visible','off');
            set(h_globalnormsselect,'Visible','off');
            set(h_highpassfilterselect,'Visible','off');
            set(h_highpassfiltervalue,'Visible','off');
            set(h_maskselect,'Visible','off');
            set(h_AR1select,'Visible','off');
            set(h_covariateselect,'Visible','off');
            set(h_linear_components,'Visible','off');
            set(h_artmodel,'Visible','off');
            set(h_trialmodel,'Visible','off');
            set(h_trial_inter_model,'Visible','off');
            
        end
        
        fsb_show_design(sandbox,ropts)
    end

%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
% Model derivatives?
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
function Derivativesselect_Callback(source, eventdata)


        if (get(h_derivativesselect,'Value') == get(h_derivativesselect,'Max')) ;
            ropts.derivs = [1 1];
        else
            ropts.derivs = [0 0];
        end

end

%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
% Do Global Normalization
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
function Globnormselect_Callback(source, eventdata)

        if (get(h_globalnormsselect,'Value') == get(h_globalnormsselect,'Max')) ;
            ropts.global = 'Scaling';
        else
            ropts.global = 'None';
        end

end

%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
% Mask data
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
function Maskselect_Callback(source, eventdata)

        if (get(h_maskselect,'Value') == get(h_maskselect,'Max')) ;
            ropts.mask = maskimage;
        else
            ropts.mask = '';
        end

end

%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
% Run AR(1) correction
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
function AR1select_Callback(source, eventdata)

        if (get(h_AR1select,'Value') == get(h_AR1select,'Max')) ;
            ropts.cvi = 'AR(1)';
        else
            ropts.cvi = '';
        end

end

%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
% High pass filter data
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
function highpassfilterselect_Callback(source, eventdata)

        if (get(h_highpassfilterselect,'Value') == get(h_highpassfilterselect,'Max')) ;
            hpfstring = get(h_highpassfiltervalue,'String');        
            ropts.hpf = str2num(hpfstring);
        else
            ropts.hpf = 'Inf';
        end

end

%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
% Model linear components
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
function lin_comp_select_Callback(source, eventdata)

        if (get(h_linear_components,'Value') == get(h_linear_components,'Max')) ;
            ropts.lincomp = 1;
        else
            ropts.lincomp = 0;
        end

end

%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
% Label selected trials as artefacts
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
function trialmodel_select_Callback(source, eventdata)

        if (get(h_trialmodel,'Value') == get(h_trialmodel,'Max')) ;
            ropts.trialmod = 1;
        else
            ropts.trialmod = 0;
        end

end

%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
% Label artefact volumes in model
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
function artmodel_select_Callback(source, eventdata)

        if (get(h_artmodel,'Value') == get(h_artmodel,'Max')) ;
            ropts.artmod = 1;
        else
            ropts.artmod = 0;
        end

end

%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
% Label all intertrial volumes as artefacts in model
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

function trial_inter_model_Callback(source, eventdata)

        if (get(h_trial_inter_model,'Value') == get(h_trial_inter_model,'Max')) ;
            ropts.trialintermod = 1;
        else
            ropts.trialintermod = 0;
        end

end


%~~~~~~~~~~~~~~~~~~~~~
% Select if contrasts should be set up and estimated
%~~~~~~~~~~~~~~~~~~~~~

    function Contrastselect_Callback(source, eventdata)

        if (get(h_contrastselect,'Value') == get(h_contrastselect,'Max')) ;
            set(h_contrast_name1,'Visible','on')
            set(h_contrast_vector1,'Visible','on')
            set(h_contrast_name2,'Visible','on')
            set(h_contrast_vector2,'Visible','on')
            set(h_contrast_name3,'Visible','on')
            set(h_contrast_vector3,'Visible','on')
            set(h_contrast_name4,'Visible','on')
            set(h_contrast_vector4,'Visible','on')
           ropts.do(5) = 1;
        else
            set(h_contrast_name1,'Visible','off')
            set(h_contrast_vector1,'Visible','off')
            set(h_contrast_name2,'Visible','off')
            set(h_contrast_vector2,'Visible','off')
            set(h_contrast_name3,'Visible','off')
            set(h_contrast_vector3,'Visible','off')
            set(h_contrast_name4,'Visible','off')
            set(h_contrast_vector4,'Visible','off')
            ropts.do(5) = 0;
        end
    end

%~~~~~~~~~~~~~~~~~~~~~
% Contrast callbacks
%~~~~~~~~~~~~~~~~~~~~~

    function Contrastname1_Callback(source,eventdata)
        contrastname = get(h_contrast_name1,'String');
        ropts.contrastname{1} = contrastname;
                contrastvector = get(h_contrast_vector1,'String');
        ropts.contrastvector{1} = contrastvector;
    end

    function Contrastname2_Callback(source,eventdata)
        contrastname = get(h_contrast_name2,'String');
        ropts.contrastname{2} = contrastname;
               contrastvector = get(h_contrast_vector2,'String');
        ropts.contrastvector{2} = contrastvector;
    end


    function Contrastname3_Callback(source,eventdata)
        contrastname = get(h_contrast_name3,'String');
        ropts.contrastname{3} = contrastname;
               contrastvector = get(h_contrast_vector3,'String');
        ropts.contrastvector{3} = contrastvector;
    end


    function Contrastname4_Callback(source,eventdata)
        contrastname = get(h_contrast_name4,'String');
        ropts.contrastname{4} = contrastname;
                contrastvector = get(h_contrast_vector4,'String');
        ropts.contrastvector{4} = contrastvector;
    end



%~~~~~~~~~~~~~~~~~~~~~~~~~~
% Now just run the pipeline
%~~~~~~~~~~~~~~~~~~~~~~~~~~

    function run_pipeline_Callback(source,eventdata)

        %~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        % Prepare directories and write files
        %~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        ropts.prefix = [];
        ropts.prefix2 = [];

        if ropts.do(3) ==1
            ropts.prefix = 's';
        end

        if ropts.do(1) == 1
            ropts.prefix = [ropts.prefix 'w'];
            ropts.prefix2 = 'w';
        end

        if ropts.do(2) == 1
            ropts.prefix = [ropts.prefix 'r'];
            ropts.prefix2 = [ropts.prefix2 'r'];
        end

        tmp  = prepare_directories(sandbox,idat,ropts);
        fsb_spm_jobman2(sandbox,ropts,tmp)

    end


%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
% Run just the coregistration part of the analysis - currently disabled
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
%     function TestCoregistration_Callback(source, eventdata) % Fails
% 
%         %~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
%         % Set up Ropts
%         ropts.do = [1 1 0]; % Run preprocessing and model, no contrasts
%         ropts.ver = 'SPM5'; % Use SPM5
%         ropts.what = 0; % Do not reslice the images
%         %ropts.srt = 5;
% 
%         %~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
%         % Prepare the directories for SPM
%         %~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
%         tmp  = prepare_directories(sandbox,idat,ropts);
%         fsb_spm_jobman_test(sandbox);
%     end

%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
% prepare directories for SPM operations
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

    function tmp = prepare_directories(sandbox,idat,ropts)

        %~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        % Create directories
        %~~~~~~~~~~~~~~~~~~~~~~~~~~~~

        disp(['Writing images for ' ropts.ver ' analysis']);
        newpath = ['SPM_' date];
        mkdir (newpath);
        cd (newpath);
        mkdir analysis2;
        mkdir images; cd images;

        %~~~~~~~~~~~~~~~~~~~~~~~~~~~
        % Set up file names and headers used
        %~~~~~~~~~~~~~~~~~~~~~~~~~~~
        
        name = [sandbox.name(1:3) '_'];
        idat = int16(idat);

        if isfield(sandbox,'hdr') && ~isempty(sandbox.hdr);
            template_name = sandbox.hdr;
        else
            template_name = 'template.hdr';            
        end

        %~~~~~~~~~~~~~~~~~~~~~~~~~~~
        % Handle artefact labeling
        %~~~~~~~~~~~~~~~~~~~~~~~~~~~

        discard2 = zeros(size(sandbox.intrial,1),1);

        if ~isfield(sandbox,'discard')
            sandbox.discard = [];

        else
            sandbox.discard(sandbox.discard<=0) =[];
        end

        if ropts.artmod ~=1;
            sandbox.discard = [];
        end

        if ropts.trialmod ==1;
            temp = find(sandbox.intrial(:,1)>1);
            sandbox.discard = [sandbox.discard; temp];
            sandbox.discard = unique(sandbox.discard);
        end
        
        if ropts.trialintermod ==1;
            temp = find(sandbox.intrial(:,1)==0);
            sandbox.discard = [sandbox.discard; temp];
            sandbox.discard = unique(sandbox.discard);
        end


        discard2(sandbox.discard) = 1;

        %~~~~~~~~~~~~~~~~~~~~~~~~~~~
        % Write actual files
        %~~~~~~~~~~~~~~~~~~~~~~~~~~~

        
        y = 0;
        for x = 1:max(sandbox.intrial(:,ropts.srt));

            otto = find (sandbox.intrial(:,ropts.srt)==x);
            if isempty(otto)
                disp(['No data for trial ' num2str(x)])
            else
                y = y+1;
                idat_red = idat(:,:,:,otto);
                filename2 = sprintf('%04.0f', y);
                tmp.name{y} = [name filename2 '_'];
                fsb_img_write(idat_red,tmp.name{y},template_name,4,1);
                sandbox.name = name;
                tmp.hemodynamics{y} = sandbox.hemodynamics(otto,:);
                tmp.discard{y} = discard2(otto,:);

            end
        end

        cd ..
    end

end
